package com.jlf.core.annotation.restful;

import com.jlf.core.annotation.restful.method.*;
import io.micrometer.common.util.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;

import java.lang.reflect.Method;

/**
 * 自定义restful的辅助工具
 *
 * @author wujr
 * 2023/8/2
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/2 1.0 新增]
 */
public class RestfulToolkit {
    public static boolean isProduceJson(MethodParameter returnType){
        String[] produces = produces(returnType);
        if (produces == null){
            return true;
        }
        for (String produce : produces){
            if (StringUtils.isBlank(produce)){
                continue;
            }
            if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(produce)){
                // 返回的不是json格式
                return false;
            }
        }
        return true;
    }
    public static String[] produces(MethodParameter returnType){
        Method method = returnType.getMethod();
        if (method == null){
            return null;
        }
        RestfulGet restfulGet = method.getDeclaredAnnotation(RestfulGet.class);
        if (restfulGet != null){
            return restfulGet.produces();
        }

        RestfulPost restfulPost = method.getDeclaredAnnotation(RestfulPost.class);
        if (restfulPost != null){
            return restfulPost.produces();
        }

        RestfulPut restfulPut = method.getDeclaredAnnotation(RestfulPut.class);
        if (restfulPut != null){
            return restfulPut.produces();
        }

        RestfulDelete restfulDelete = method.getDeclaredAnnotation(RestfulDelete.class);
        if (restfulDelete != null){
            return restfulDelete.produces();
        }

        RestfulPatch restfulPatch = method.getDeclaredAnnotation(RestfulPatch.class);
        if (restfulPatch != null){
            return restfulPatch.produces();
        }

        RestfulApi restfulApi = method.getDeclaredAnnotation(RestfulApi.class);
        if (restfulApi != null){
            return restfulApi.produces();
        }
        return null;
    }
}
